#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：组合模式.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/3/1 23:54 
"""

"""
组合模式（Composite Pattern）
模式解释：
组合模式允许将对象组合成树形结构以表示部分-整体层次结构，使得客户端统一处理单个对象和组合对象。
"""

from abc import ABC, abstractmethod


class Component(ABC):
	@abstractmethod
	def operation(self):
		pass


class Leaf(Component):
	def operation(self):
		return "Leaf operation."


class Composite(Component):
	def __init__(self):
		self._children = []

	def add(self, component):
		self._children.append(component)

	def remove(self, component):
		self._children.remove(component)

	def operation(self):
		results = []
		for child in self._children:
			results.append(child.operation())
		return f"Composite operation:\n{' '.join(results)}"


leaf1 = Leaf()
leaf2 = Leaf()
composite = Composite()
composite.add(leaf1)
composite.add(leaf2)

print(composite.operation())
